package com.yzly.demo.service.demo;

import com.alibaba.fastjson.JSONObject;
import com.yzly.demo.utils.RedisUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;

@Service
@Transactional
@CacheConfig(cacheNames = "test")
public class TestService {

    @Inject
    private RedisUtils redisUtils;

    //    @Cacheable(key = "'test_'+#id")
    public JSONObject getTestJson(Integer id) {
        if (redisUtils.get("hello") != null) {
            JSONObject j = (JSONObject)redisUtils.get("hello");
            System.out.println(j.get("mes"));
            return j;
        }
        System.out.println("去数据库查询");
        JSONObject json = new JSONObject();
        json.put("code", 20000);
        json.put("mes", "测试成功");
        json.put("data", "hello word!");
        redisUtils.set("hello", json, 1000l);
        return json;
    }

    @CacheEvict(allEntries = true)
    public void cleanCache() {
        System.out.println("清除缓存");
    }
}
